<template>
	<div class="container">
		<h2>{{ id ? '修改' : '创建' }}主要物资合同</h2>
		<a-form ref="formRef" :model="formState" layout="vertical" @finish="saveContract">
			<a-row :gutter="20">
				<a-col :span="8">
					<a-form-item label="选择项目" name="project_id" :rules="{ required: true, message: '请选择项目' }">
						<a-select v-model:value="formState.project_id" :show-search="true" placeholder="请选择项目" :options="projectOptions" option-filter-prop="label" @change="changeProject"></a-select>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="选择计划名称" name="plan_id" :rules="{ required: true, message: '请选择计划' }">
						<a-select v-model:value="formState.plan_id" :show-search="true" placeholder="请选择计划" :options="planlist" option-filter-prop="label" @change="choosePlan"></a-select>
					</a-form-item>
				</a-col>

				<a-col :span="8">
					<a-form-item label="合同名称" name="name" :rules="{ required: true, message: '请输入合同名称' }">
						<a-input v-model:value="formState.name" placeholder="请输入合同名称" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="合同编号" name="code" :rules="{ required: true, message: '请输入合同编号' }">
						<a-input v-model:value="formState.code" placeholder="请输入合同编号" @blur="checkCode" />
					</a-form-item>
				</a-col>

				<a-col :span="8">
					<a-form-item label="选择供应商名称" name="supplier_id" :rules="{ required: true, message: '请选择供应商' }">
						<a-select v-model:value="formState.supplier_id" :show-search="true" placeholder="请选择供应商" :options="userlist" option-filter-prop="label"></a-select>
					</a-form-item>
				</a-col>

				<a-col :span="8">
					<a-form-item label="合同类型" name="price_type" :rules="{ required: true, message: '请选择价格类型' }" @change="() => formState.material_type = null">
						<a-radio-group v-model:value="formState.price_type" :disabled="[2, 3].includes(formState.material_type)">
							<a-radio :value="1">固定单价合同</a-radio>
							<a-radio :value="2">单价*浮动率合同</a-radio>
							<a-radio :value="3">单价*浮动价合同</a-radio>
						</a-radio-group>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="专项类型" name="material_type" :rules="{ required: true, message: '请选择专项类型' }">
						<a-radio-group v-model:value="formState.material_type" @change="choosemt">
							<a-radio :value="1">其他</a-radio>
							<a-radio :value="2">混凝土专项</a-radio>
							<a-radio :value="3">钢筋专项</a-radio>
						</a-radio-group>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="客户联系人" name="contact" :rules="{ required: true, message: '请输入客户联系人' }">
						<a-input v-model:value="formState.contact" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-row>
						<a-col :span="12">
							<a-form-item label="签订时间" name="sign_time" :rules="{ required: true, message: '请输入签订时间' }">
								<a-date-picker v-model:value="formState.sign_time" value-format="YYYY-MM-DD" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="合同" name="file_path" :rules="{ required: true, message: '请上传合同附件' }">
								<a-upload v-model:file-list="formState.file_path" name="upload" :action="`${baseURL}/contract/upload`" :show-upload-list="true" :headers="{ Authorization: `Bearer ${proxy.$cookies.get('token')}` }" :before-upload="beforeUpload" @change="changeUpload">
									<a-button>
										<template v-if="uploading">
											<loading-outlined />上传中...
										</template>
										<template v-else>
											<import-outlined />上传合同附件
										</template>
									</a-button>
								</a-upload>
							</a-form-item>
						</a-col>
					</a-row>

				</a-col>
				<a-col :span="8">
					<a-form-item label="采购方式" name="purchase_way_id" :rules="{ required: true, message: '请选择采购方式' }">
						<a-select v-model:value="formState.purchase_way_id" :show-search="true" placeholder="请选择采购方式" :options="purchaseWays" option-filter-prop="label"></a-select>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="付款方式" name="pay_way_id" :rules="{ required: true, message: '请选择付款方式' }">
						<a-select v-model:value="formState.pay_way_id" :show-search="true" placeholder="请选择付款方式" :options="payWays" option-filter-prop="label"></a-select>
					</a-form-item>
				</a-col>
				<template v-if="formState.material_type === 2">
					<a-col v-if="!formState.art_indexes?.length" :span="8">
						<a-form-item label="技术指标" name="art_indexes">
							<a-button type="primary" ghost @click="addArtIndex">+</a-button>
						</a-form-item>
					</a-col>
					<a-col v-for="(item, i) in formState.art_indexes" v-else :key="i" :span="8">
						<a-form-item label="技术指标" name="art_indexes">
							<a-input-group compact>
								<a-select v-model:value="item.gonghao_id" :options="artIndexesGongHaos" style="width: 150px;" placeholder="请选择技术指标" allow-clear @change="changeArtIndex(item)"></a-select>
								<a-input-number v-model:value="item.price" style="width: 40%" placeholder="请输入价格" allow-clear />
								<a-button type="primary" danger ghost @click="delArtIndex(i)">-</a-button>
								<a-button v-if="i + 1 === formState.art_indexes.length" type="primary" ghost @click="addArtIndex">+</a-button>
							</a-input-group>
						</a-form-item>
					</a-col>
				</template>
				<!--				<a-col v-if="formState.material_type === 2" :span="8">-->
				<!--					<a-form-item label="技术指标" name="art_indexes">-->
				<!--						<template v-if="!formState.art_indexes?.length">-->
				<!--							<a-button type="primary" ghost @click="addArtIndex">+</a-button>-->
				<!--						</template>-->
				<!--						<template v-else>-->
				<!--							<a-input-group v-for="(item, i) in formState.art_indexes" :key="i" compact class="pt-2">-->
				<!--								<a-select v-model:value="item.gonghao_id" :options="artIndexesGongHaos" style="width: 150px;" placeholder="请选择技术指标" allow-clear @change="changeArtIndex(item)"></a-select>-->
				<!--								<a-input-number v-model:value="item.price" style="width: 40%" placeholder="请输入价格" allow-clear />-->
				<!--								<a-button type="primary" danger ghost @click="delArtIndex(i)">-</a-button>-->
				<!--								<a-button v-if="i + 1 === formState.art_indexes.length" type="primary" ghost @click="addArtIndex">+</a-button>-->
				<!--							</a-input-group>-->
				<!--						</template>-->
				<!--					</a-form-item>-->
				<!--				</a-col>-->

				<a-col :span="24">
					<h1 style="font-size:18px;text-align: center;font-weight:bold">合同物资清单</h1>
					<div class="table-toolbar mb-3">
						<a-space>
							<a-button type="primary" @click="addMaterialModel">
								<plus-outlined />新增
							</a-button>
							<!--
							<a-button class="cache-btn" @click="handleCache">
								<DeliveredProcedureOutlined />暂存
							</a-button>
							-->
							<a-button @click="fillInBatch()">
								<BarsOutlined />批量填充
							</a-button>
						</a-space>
					</div>
					<a-table :scroll="tableScroll" :pagination="pagination" :data-source="formState.materials" :columns="planMaterialColumns" :row-key="(record) => record.key" @change="handleTableChange"> 
						<template #bodyCell="{ column, record }">
							<template v-if="column.dataIndex === 'name'">
								<a-form-item :name="['materials', record.key, 'source_id']" :rules="{ required: true, message: '请选择材料名称' }">
									<a-tree-select v-model:value="record.source_id" :show-search="true" placeholder="请选择材料名称" allow-clear :tree-data="materialOptions" tree-node-filter-prop="label" style="width:100%" @change="(id) => changeMaterial(id, record)">
										<template #title="{ label }">{{ label }}</template>
									</a-tree-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'model'">
								<a-form-item :name="['materials', record.key, 'id']" :rules="{ required: true, message: '请选择规格' }">
									<a-select v-model:value="record.id" :show-search="true" placeholder="请选择" :options="materialModelOptions[record.source_id] || []" allow-clear :field-names="{ value: 'id', label: 'model' }" style="width:100%" @change="(id) => changeModel(id, record, materialModelOptions[record.source_id])"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'intro'">
								<a-form-item :name="['materials', record.key, 'intro']">
									<a-input v-model:value="record.intro" placeholder="请输入详细规格" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'unit'">
								<a-form-item :name="['materials', record.key, 'unit']">
									<!--
									<a-select v-model:value="record.unit" :show-search="true" placeholder="请选择" :options="unitOptions" :field-names="{ value: 'name' }" style="width:100%"></a-select>
									-->
									{{ record.unit || '-' }}
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'up_per' && formState.price_type == 2">
								<a-form-item :name="['materials', record.key, 'up_per']" :rules="{ required: true, message: '请输入浮动率' }">
									<a-input-number v-model:value="record.up_per" placeholder="浮动率" suffix="%" @blur="authPriceCalculation(record)" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'up_per' && formState.price_type == 3">
								<a-form-item :name="['materials', record.key, 'up_per']" :rules="{ required: true, message: '请输入浮动价格' }">
									<a-input-number v-model:value="record.up_per" placeholder="浮动价格" @blur="authPriceCalculation(record)" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'without_tax_subprice_base'">
								<a-form-item :name="['materials', record.key, 'without_tax_subprice_base']" :rules="{ required: true, message: '请输入不含税基准价格' }">
									<a-input-number v-model:value="record.without_tax_subprice_base" placeholder="请输入不含税基准价格" @blur="authPriceCalculation(record)" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'quantity'">
								<a-form-item :name="['materials', record.key, 'quantity']" :rules="{ required: true, message: '请输入数量' }">
									<a-input-number v-model:value="record.quantity" placeholder="请输入数量" :precision="3" @blur="checkqty(record)" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'tax'">
								<a-form-item :name="['materials', record.key, 'tax']" :rules="{ required: true, message: '请输入税率' }">
									<a-input-number v-model:value="record.tax" placeholder="税率" suffix="%" @blur="authPriceCalculation(record)" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'memo'">
								<a-form-item :name="['materials', record.key, 'memo']">
									<a-input v-model:value="record.memo" placeholder="请输入备注" />
								</a-form-item>
							</template>
							<template v-else-if="column.key === 'operation'">
								<a-space>
									<!--
									<a-button type="link" @click="copyMaterialModel(record)">
										<copy-outlined />复制
									</a-button>-->

									<a-popconfirm title="确定要删除当前材料吗？" ok-text="是" cancel-text="否" @confirm="deleteMaterialModel(record.key)">
										<a-button type="link" style="color:#ff7875">
											<delete-outlined />删除
										</a-button>
									</a-popconfirm>
								</a-space>
							</template>
						</template>
						<template #summary>
							<a-table-summary-row style="background-color:#f0f0f0;font-size:12px;font-weight:bold;">
								<a-table-summary-cell :col-span="2">
									<a-typography-text>合计</a-typography-text>
								</a-table-summary-cell>

								<a-table-summary-cell v-if="Number(formState.price_type) === 1" :col-span="6"></a-table-summary-cell>
								<a-table-summary-cell v-else :col-span="8"></a-table-summary-cell>
								<a-table-summary-cell class="text-center">
									<a-typography-text>{{ formState.amount }}</a-typography-text>
								</a-table-summary-cell>

								<a-table-summary-cell></a-table-summary-cell>
								<a-table-summary-cell class="text-center">
									<a-typography-text>{{ formState.with_tax_amount }}</a-typography-text>
								</a-table-summary-cell>
								<a-table-summary-cell class="text-center">
									<a-typography-text>{{ formState.tax_amount }}</a-typography-text>
								</a-table-summary-cell>
								<a-table-summary-cell></a-table-summary-cell>
								<a-table-summary-cell></a-table-summary-cell>
								<a-table-summary-cell></a-table-summary-cell>
							</a-table-summary-row>
						</template>
					</a-table>
				</a-col>
			</a-row>

			<a-row :gutter="20">
				<a-col :span="24" class="py-4 text-center">
					<a-space>
						<!--
						<a-button class="cache-btn" @click="handleCache">
							<DeliveredProcedureOutlined />暂存
						</a-button>
						-->

						<a-button v-if="!formState.id || ![0, 1, 2].includes(formState.workflow_status)" type="primary" html-type="submit" :loading="loading">
							<save-outlined />保存
						</a-button>

						<a-workflow v-if="formState.id" v-model:status="formState.workflow_status" module="contract" :target-id="formState.id" :project-id="formState.project_id" :code="formState.code" :user-id="formState.opr_id" @submit="submitPurchase"></a-workflow>
						<a-button @click="closeTab('/contract')">
							<close-outlined />关闭
						</a-button>
					</a-space>
				</a-col>
			</a-row>
		</a-form>
		<a-modal v-model:visible="visible" :width="400" title="批量填充" @ok="fillIn">
			<a-form ref="formFillRef" :model="fillInData">
				<a-row>
					<a-col :span="24">
						<a-form-item label="填充类型" name="column_key" :rules="{ required: true, message: '请选择填充类型' }">
							<a-select v-model:value="fillInData.column_key" :show-search="true" placeholder="请选择填充类型" :options="innerFillColumnOptions" option-filter-prop="label"></a-select>
						</a-form-item>
					</a-col>
					<a-col v-if="fillInData.column_key === 'plan_material'" :span="24">
						<a-form-item label="选择子计划" name="id" :rules="{ required: true, message: '请选择子计划物料单' }">
							<a-select v-model:value="fillInData.id" :show-search="true" placeholder="请选择子计划物料单" :options="planOptions" option-filter-prop="label"></a-select>
						</a-form-item>
					</a-col>
					<a-col v-else :span="24">
						<a-form-item label="填充内容" name="column_val" :rules="{ required: true, message: '请输入填充内容' }">
							<a-input v-model:value="fillInData.column_val" placeholder="请输入填充内容" />
						</a-form-item>
					</a-col>
				</a-row>
				<!-- <a-row v-if="popType == 2">
					<a-col :span="24">
						<a-form-item label="选择子计划" name="id" :rules="{ required: true, message: '请选择子计划物料单' }">
							<a-select v-model:value="fillInData.id" :show-search="true" placeholder="请选择子计划物料单" :options="planOptions" option-filter-prop="label"></a-select>
						</a-form-item>
					</a-col>
				</a-row> -->
		
			</a-form>
		</a-modal>
	</div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance, inject, watch } from "vue";
import { DeleteOutlined, SaveOutlined, CloseOutlined, DeliveredProcedureOutlined, BarsOutlined, LoadingOutlined, ImportOutlined, PlusOutlined } from "@ant-design/icons-vue";
import { baseURL } from "../utils/request";
//import dayjs from "dayjs";
import { post, listToTree, postJson } from "../utils";
import { useRoute, useRouter } from "vue-router";
import { add, subtract } from "../utils/operation.js";
import { AWorkflow } from "@/components/index.js";

const router = useRouter();
//缓存数据
/*
const handleCache = () => {
	console.log(formState.value);

	localStorage.setItem("contract-save", JSON.stringify(formState.value));
	proxy.$message.success("缓存成功");
};
*/
const popType = ref({})
// 批量填写弹出框 
const fillInBatch = (type) => {
	fillInData.value = {};
	visible.value = true;
};

const pagination = ref({
	current: 1,
	pageSize: 50,
});
const handleTableChange = (pag, filters, sorter) => {
	Object.assign(pagination.value, 
		{
			current: pag.current,
			pageSize: 50,
		}
	)
}
const toLastPage = () => {
	const total = formState.value.materials.length;
	const lastPage = Math.ceil(total / pagination.value.pageSize);
	Object.assign(pagination.value, 
		{
			current: lastPage,
			pageSize: 50,
			total: total,
		}
	)
}

// 批量填充
const fillIn = () => {
	formFillRef.value.validate().then(() => {
		if (fillInData.value.column_key !== 'plan_material') {
			proxy.$message.destroy();
			for (const material of formState.value.materials) {
				material[fillInData.value["column_key"]] = fillInData.value["column_val"];
				authPriceCalculation(material);
			}
			proxy.$message.success("填充成功", 1);
		} else {
			// 请求子计划物料列表接口 渲染物料列表数据 对比有没有重复
			post("plan/info", { id: fillInData.value["id"] }).then(data => {
				const { materials } = data;
				const materialIds = formState.value.materials.map(item => item.id);
				for (const material of materials) {
					if (materialIds.includes(material.id)) continue;
					formState.value.materials.push({
						id: material.id,
						source_id: material.source_id,
						unit: material.unit,
						key: formState.value.materials.length,
					})
				}
				toLastPage()
			})
		}
		visible.value = false;
	});
};

const route = useRoute();
const id = computed(() => {
	return route.params.id || 0;
});

const formState = ref({ materials: [] });
const fillInData = ref({});
const planlist = ref([]); //	计划列表
const userlist = ref([]); // 供应商列表
const uploading = ref(false);
const formRef = ref();
const formFillRef = ref();
const visible = ref(false);
const timeunitOptions = ref([]);
const { proxy } = getCurrentInstance();
const projectOptions = ref([]);
const purchaseWays = ref([]);
const payWays = ref([]);
const artIndexesGongHaos = ref([]);
watch(() => formState.value.materials.length, (len) => {
	pagination.value.total = len;
})
post("department/projects?type=3", { page_size: 10000 }).then(({ data }) => {
	projectOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
post("dictionary", { root_id: 1501 }).then((data) => {
	purchaseWays.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});

post("dictionary", { root_id: 1069 }).then((data) => {
	artIndexesGongHaos.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
post("dictionary", { root_id: 1506 }).then((data) => {
	payWays.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
//选择项目对应的计划
const changeProject = value => {
	const project_id = value;
	post("plan", { type: 1, project_id, workflow_status: 2 }).then(({ data }) => {
		planlist.value = data.map(d => {
			return {
				value: d.id,
				label: d.name
			};
		});

		choosePlan("");
	});
};
const addMaterialModel = () => {
	if (!formState.value.purchase_way_id || !formState.value.pay_way_id || !formState.value.name || !formState.value.code || !formState.value.plan_id || !formState.value.supplier_id || !formState.value.price_type || !formState.value.material_type || !formState.value.contact || !formState.value.file_path) {
		proxy.$message.error("请将基本信息填写完善再录入物资清单");
		return;
	}
	formState.value.materials.push({ key: formState.value.materials.length });
	toLastPage()
};
const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 680 }));
post("dictionary", { root_code: "MATERIAL_TIMEUNIT" }).then(data => {
	timeunitOptions.value = data;
});
const fillColumnOptions = [
	{
		label: "税率%",
		value: "tax"
	},
	{
		label: "浮动价格(±)",
		value: "up_per"
	},
	{
		label: "浮动比率±(%)",
		value: "up_per"
	},
	{
		label: "子计划物料",
		value: "plan_material"
	}
];
const innerFillColumnOptions = computed(() => {
	let options = [];
	switch (parseInt(formState.value.price_type)) {
	case 3:
		options = fillColumnOptions.filter(column => column.label !== "浮动比率±(%)");
		break;
	case 2:
		options = fillColumnOptions.filter(column => column.label !== "浮动价格(±)");
		break;
	case 1:
		options = fillColumnOptions.filter(column => column.value !== "up_per");
		break;
	}
	return options;
});

post("dictionary", { root_code: "MATERIAL_UNIT" }).then(data => {
	unitOptions.value = data;
});


const planMaterialColumns = computed(() => {
	let columns = [
		{
			title: "ID",
			dataIndex: "key",
			width: 60,
			align: "center",
			customRender: ({ text, record, index, column }) => {
				return text + 1;
			}
		},
		{
			title: "物资名称",
			dataIndex: "name",
			width: 250,
			ellipsis: true,
			align: "center"
		},
		{
			title: "型号规格",
			dataIndex: "model",
			width: 150,
			ellipsis: true,
			align: "center"
		},
		{
			title: "详细规格",
			dataIndex: "intro",
			width: 150,
			ellipsis: true,
			align: "center"
		},
		{
			title: "单位",
			dataIndex: "unit",
			width: 120,
			align: "center"
		},
		{
			title: "数量",
			dataIndex: "quantity",
			width: 100,
			align: "center"
		},
		{
			title: formState.value.price_type === 1 ? "不含税单价(元)" : "不含税基准价格(元)",
			dataIndex: "without_tax_subprice_base",
			width: 150,
			align: "center"
		},
		{
			title: "税率%",
			dataIndex: "tax",
			width: 120,
			align: "center"
		},
	]
	if (Number(formState.value.price_type) === 2) {
		columns.push({
			title: "浮动比率±(%)",
			dataIndex: "up_per",
			width: 120,
			align: "center"
		})
	} else if (Number(formState.value.price_type) === 3) {
		columns.push({
			title: "浮动价格(±)",
			dataIndex: "up_per",
			width: 120,
			align: "center"
		},)
	}
	columns = [
		...columns,
		...(formState.value.price_type !== 1 ? [{
			title: "不含税单价(元)",
			dataIndex: "without_tax_subprice",
			width: 120,
			align: "center"
		}] : []),
		{
			title: "不含税总价(元)",
			dataIndex: "without_tax_amount",
			width: 120,
			align: "center"
		},
		{
			title: "含税单价(元)",
			dataIndex: "with_tax_subprice",
			width: 120,
			align: "center"
		},
		{
			title: "含税总价",
			dataIndex: "with_tax_amount",
			width: 120,
			align: "center"
		},
		{
			title: "税额",
			dataIndex: "tax_amount",
			width: 120,
			align: "center"
		},
		{
			title: "操作",
			key: "operation",
			sorter: false,
			fixed: "right",
			width: 200,
			align: "center"
		}
	]
	return columns;
})
const unitOptions = ref([]);
const checkCode = async () => {
	if (!formState.value.code) return;
	post("contract/check/code", { code: formState.value.code, id: id.value }).catch(err => {
		proxy.$message.error(err);
		formState.value.code = null;
	});
}
const choosemt = value => {
	if ([2, 3].includes(formState.value.material_type)) {
		formState.value.price_type = formState.value.material_type;
	}
	formState.value.art_indexes = [{}];
	formState.value.materials = [];
};

onMounted(async () => {
	/*
	const cacheData = localStorage.getItem("contract-save");
	formState.value = JSON.parse(cacheData) || formState.value;
	*/
	if (id.value) {
		await post("contract/info", { id: id.value }).then(data => {
			data.file_path = JSON.parse(data.file_path || "[]");
			let amount = 0;
			let wt_amount = 0;
			let t_amount = 0;
			if (data.art_indexes) {
				data.art_indexes = JSON.parse(data.art_indexes);
			} else {
				data.art_indexes = [{}];
			}
			if (!data.art_indexes.length) {
				data.art_indexes = [{}];
			}
			data.materials = data.materials.map((d, i) => {
				d.key = i;

				const { intro, unit, quantity, without_tax_subprice_base, down_per, up_per, without_tax_subprice, without_tax_amount, with_tax_subprice, with_tax_amount, tax_amount, tax, standard, add_time, use_time, time_unit, useto, memo } = d.ContractMaterial;
				d.intro = intro;
				d.unit = unit;
				d.quantity = quantity;
				d.without_tax_subprice_base = without_tax_subprice_base;
				d.down_per = down_per;
				d.up_per = up_per;
				d.without_tax_subprice = without_tax_subprice;
				d.without_tax_amount = without_tax_amount;
				d.tax = tax;
				d.with_tax_subprice = with_tax_subprice;
				d.with_tax_amount = with_tax_amount;
				d.tax_amount = tax_amount;

				d.standard = standard;
				d.add_time = add_time;
				d.use_time = use_time;
				d.time_unit = time_unit;
				d.useto = useto;
				d.memo = memo;
				wt_amount = parseFloat(wt_amount) + parseFloat(with_tax_amount);
				amount = parseFloat(amount) + parseFloat(without_tax_amount);
				t_amount = parseFloat(t_amount) + parseFloat(tax_amount);
				return d;
			});
			formState.value = data;
			formState.value.with_tax_amount = wt_amount.toFixed(2);
			formState.value.tax_amount = t_amount.toFixed(2);

			return data;
		});
		// 默认进来计划名称有值
		if (formState.value.plan_id) {
			planList()
		}
		pagination.value["total"] = formState.value.materials.length
	} else {
		formState.value.type = 1;
		formState.value.price_type = 1;
	}

	const { project_id, plan_id } = formState.value;
	if (project_id) {
		await post("plan", { type: 1, page_size: Infinity, project_id, workflow_status: 2 }).then(({ data }) => {
			planlist.value = data.map(d => {
				return {
					value: d.id,
					label: d.name
				};
			});
		});
	}

	if (plan_id) {
		await post("dictionary", { plan_id, workflow_status: 2 }).then(data => {
			materialOptions.value = data;
			post("material", { source_id: data.map(d => d.id).join(","), plan_id, page_size: Infinity, workflow_status: 2 }).then(({ data }) => {
				materialModelOptions.value = (() => {
					const array = [];
					data.forEach(d => {
						if (!array[d.source_id]) array[d.source_id] = [];

						if (d.attr) d.model = `${d.model}（${d.attr}）`;

						array[d.source_id].push(d);
					});

					return array;
				})(data);
			});
		});
	}

	post("user", { is_supplier: 1, page_size: Infinity, status: 1 }).then(({ data }) => {
		userlist.value = data.map(d => {
			return {
				value: d.id,
				label: d.company_name || d.mobile
			};
		});
	});
});
const planOptions = ref([])
// 查询子计划列表数据
const planList = () => {
	planOptions.value = []
	post("plan", { type: 1, parent_id: formState.value.plan_id, workflow_status: 2 }).then(res => {
		const { data } = res
		data.forEach(item => {
			planOptions.value.push({ value: item.id, label: item.name })
		})
	})
}
// 选择计划名称触发
const choosePlan = value => {
	const plan_id = value;
	formState.value.plan_id = plan_id;
	formState.value.materials = []; //清空物资清单
	if (!value) return;
	post("dictionary", { plan_id: plan_id, workflow_status: 2 }).then(data => {
		//	const { root_id: rootId } = data[0] || {};
		materialOptions.value = data;
		//获取所有规格
		post("material", { source_id: data.map(d => d.id).join(","), plan_id: plan_id, page_size: Infinity, workflow_status: 2 }).then(({ data }) => {
			materialModelOptions.value = (() => {
				const array = [];
				data.forEach(d => {
					if (!array[d.source_id]) array[d.source_id] = [];

					if (d.attr) d.model = `${d.model}（${d.attr}）`;

					array[d.source_id].push(d);
				});

				return array;
			})(data);
		});
	});

	post("plan/info", { id: value }).then(data => {
		formState.value.type = data.type;
	});
	// 查询子计划列表数据
	planList() 
};
//检验数量
const checkqty = async record => {
	if (record.id > 0) {
		//当前的物资数量
		let current_qty = 0;
		formState.value.materials.map(d => {
			if (d.id === record.id) {
				current_qty = current_qty + parseFloat(d.quantity);
			}
		});
		const contractHistory = await post("contract/all", { plan_id: formState.value.plan_id });
		const history_current_qty = contractHistory.reduce((target, item) => {
			if (parseInt(item.id) === parseInt(route.params.id)) return target;
			for (const material of item.materials) {
				if (material.id !== record.id) {
					continue;
				}
				target = add([target, material.ContractMaterial.quantity]);
			}
			return target;
		}, 0);
		post("contract/plan_num", { plan_id: formState.value.plan_id, material_id: record.id }).then(num => {
			if (current_qty > num - history_current_qty) {
				proxy.$message.error("合同清单数量不能超过计划数量");
				let now_qty = add([subtract([num, history_current_qty, current_qty]), record.quantity]);
				if (now_qty < 0) {
					now_qty = 0;
				}
				formState.value.materials[record.key]["quantity"] = now_qty;
			}

			authPriceCalculation(record);
		});
	}
};
//上传前校验
const beforeUpload = file => {
	return new Promise(resolve => {
		uploading.value = true;
		if (file.type !== "application/pdf") {
			proxy.$message.error("只能上传PDF文件");
			uploading.value = false;
			return false;
		}

		const isLt10M = file.size / 1024 / 1024 < 20;
		if (!isLt10M) {
			proxy.$message.error("只能上传10MB以下文件");
			uploading.value = false;
			return false;
		}

		resolve(true);
	});
};
// 上传并提交文件
const changeUpload = ({ file }) => {
	if (file.status === "done") {
		formState.value.file_path = [
			{
				name: file.name,
				url: file.response.data.url
			}
		];
		formState.value.file_path = formState.value.file_path.filter((item) => item.url);
		uploading.value = false;
		proxy.$message.success("上传成功");
	}
	if (!file.status) {
		formState.value.file_path = formState.value.file_path.filter((item) => item.url);
	}
};
// 自动补全价格
const authPriceCalculation = (record) => {
	if (!(record.without_tax_subprice_base > 0)) return;
	if (!record.quantity) return;
	if (!(Number(record.tax) >= 0)) return;
	const priceType = parseInt(formState.value.price_type);
	if (priceType !== 1 && typeof Number(record.up_per) !== 'number') return;
	if (priceType === 1) {
		record.without_tax_subprice = record.without_tax_subprice_base;
		record.with_tax_subprice = record.without_tax_subprice * 100 * ((1 + record.tax / 100) * 1000) / 100000;
	} else if (priceType === 2) {
		record.without_tax_subprice = record.without_tax_subprice_base * 100 * ((1 + record.up_per / 100) * 1000) / 100000;
		record.with_tax_subprice = record.without_tax_subprice * 100 * ((1 + record.tax / 100) * 1000) / 100000;
	} else if (priceType === 3) {
		record.without_tax_subprice = add([record.without_tax_subprice_base, record.up_per], 2);
		record.with_tax_subprice = record.without_tax_subprice * 100 * ((1 + record.tax / 100) * 1000) / 100000;
	}
	record.without_tax_amount = record.without_tax_subprice * 100 * (record.quantity * 1000) / 100000;
	record.with_tax_amount = record.with_tax_subprice * 100 * (record.quantity * 1000) / 100000;
	record.tax_amount = subtract([record.with_tax_amount, record.without_tax_amount], 2);
	calAmount();
}
//计算总额
const calAmount = () => {
	let amount = 0;
	let with_tax_amount = 0;
	let tax_amount = 0;

	formState.value.materials.map(d => {
		const formatColumn = ["with_tax_subprice", "with_tax_amount", "without_tax_subprice", "without_tax_amount", "quantity"];
		for (const key of formatColumn) {
			if (!d[key] || parseFloat(d[key]) === 0 || d[key] < 0) {
				d[key] = null;
			} else if (key !== "quantity") {
				d[key] = parseFloat(d[key] || 0).toFixed(2);
			}
		}
		if (d.with_tax_subprice && d.without_tax_subprice && parseFloat(d.with_tax_subprice) < parseFloat(d.without_tax_subprice)) {
			proxy.$message.error("含税单价不能小于不含税单价");
			d.with_tax_subprice = null;
		}

		if (d.with_tax_amount && d.without_tax_amount && parseFloat(d.with_tax_amount) < parseFloat(d.without_tax_amount)) {
			proxy.$message.error("含税总价不能小于不含税总价");
			d.with_tax_amount = null;
		}
		// d.up_per = parseFloat(d.up_per || 0).toFixed(2);
		// d.down_per = parseFloat(d.down_per || 0).toFixed(2);
		// d.tax = parseFloat(d.tax || 0).toFixed(2);
		//
		// d.tax_amount = parseFloat(d.tax_amount || 0).toFixed(2);
		if (d.with_tax_amount && d.without_tax_amount) {
			d.tax_amount = subtract([d.with_tax_amount, d.without_tax_amount]);
		}
		amount += parseFloat(d.without_tax_amount || 0);
		with_tax_amount += parseFloat(d.with_tax_amount || 0);
		tax_amount += parseFloat(d.tax_amount || 0);
	});

	formState.value.amount = parseFloat(amount).toFixed(2);
	formState.value.with_tax_amount = parseFloat(with_tax_amount).toFixed(2);
	formState.value.tax_amount = parseFloat(tax_amount).toFixed(2);
};
const loading = ref(false)
const saveContract = () => {
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();
			for (const artIndex of formState.value.art_indexes) {
				// if (!!artIndex.gonghao_id ^ !!artIndex.price) {
				// 	proxy.$message.error("请完善技术指标");
				// 	return;
				// }
				if (artIndex.gonghao_id && !(parseFloat(artIndex.price) >= 0)) {
					proxy.$message.error("请完善技术指标");
					return;
				}
			}
			const { id, name, type, price_type, material_type, code, contact, file_path, project_id, plan_id, supplier_id, sign_time, amount, with_tax_amount, tax_amount, materials, purchase_way_id, pay_way_id } = formState.value;

			const params = {
				id,
				name,
				type,
				price_type,
				material_type,
				code,
				contact,
				file_path,
				project_id,
				plan_id,
				supplier_id,
				sign_time,
				amount,
				with_tax_amount,
				tax_amount,
				materials,
				purchase_way_id,
				pay_way_id
			};
			params.file_path = JSON.stringify(params.file_path);
			if (formState.value.art_indexes && formState.value.art_indexes.length) {
				params.art_indexes = JSON.stringify(formState.value.art_indexes.filter(d => d.gonghao_id && d.price));
			} else {
				params.art_indexes = JSON.stringify([]);
			}

			if (!params.materials.length) {
				proxy.$message.error("请添加材料清单");
				return;
			}
			for (const material of params.materials) {
				// if (formState.value.price_type === 2 && !parseFloat(material.up_per) && !parseFloat(material.down_per)) {
				// 	proxy.$message.error("浮动价格合同必须输入浮动比率");
				// 	return;
				// }
				if (!material.with_tax_amount || !material.without_tax_amount) {
					proxy.$message.error("请完善合同材料清单信息");
					return;
				}
			}
			params.materials = JSON.stringify(
				params.materials.map(({ id, intro, unit, quantity, without_tax_subprice_base, down_per, up_per, without_tax_subprice, without_tax_amount, tax, with_tax_amount, with_tax_subprice, tax_amount, memo }) => {
					return {
						id,
						intro,
						unit,
						quantity,
						without_tax_subprice_base,
						down_per,
						up_per,
						without_tax_subprice,
						without_tax_amount,
						tax,
						tax_amount,
						with_tax_subprice,
						with_tax_amount,
						memo
					};
				})
			);
			loading.value = true
			postJson("contract/save", params)
				.then(data => {
					loading.value = false
					if (id) {
						proxy.$message.success("合同修改成功", 1);
					} else {
						proxy.$message.success("合同创建成功", 1);
						router.push(`/contract/edit/${data?.id}`);
					}
					/*
					closeTab("/contract");
					localStorage.removeItem("contract-save");
					*/
				})
				.catch(err => {
					proxy.$message.error(err);
				});
		})
		.catch(err => {});
};

post("dictionary", { root_code: "MATERIAL_UNIT" }).then(data => {
	unitOptions.value = data;
});

const materialOptions = ref([]);
const materialModelOptions = ref({});

// post("dictionary", { root_code: "MATERIAL_CATEGORY" }).then(data => {
// 	const { root_id: rootId } = data[0] || {};
// 	materialOptions.value = listToTree(data, rootId);
//
// 	//获取所有规格
// 	post("material", { source_id: data.map(d => d.id).join(","), plan_id: formState.value.plan_id, page_size: Infinity }).then(({ data }) => {
// 		materialModelOptions.value = (() => {
// 			const array = [];
// 			data.forEach(d => {
// 				if (!array[d.source_id]) array[d.source_id] = [];
//
// 				if (d.attr) d.model = `${d.model}（${d.attr}）`;
//
// 				array[d.source_id].push(d);
// 			});
//
// 			return array;
// 		})(data);
// 	});
// });

const changeMaterial = (id, record) => {
	//强制选择规格
	record.id = null;

	if (!id) return;

	post("material", { source_id: id, plan_id: formState.value.plan_id, page_size: Infinity, workflow_status: 2 }).then(({ data }) => {
		materialModelOptions.value[id] = data.map(d => {
			if (d.attr) d.model = `${d.model}（${d.attr}）`;

			return d;
		});
	});
};

const changeModel = (id, record, options) => {
	const { unit = "" } = options.find(d => d.id === id);
	if (formState.value.materials.filter(d => d.id === id).length > 1) {
		record.id = null;
		return proxy.$message.error("该物料规格已存在合同列表，请选择其他规格或物料");
	}
	formState.value.materials.find(d => d.key === record.key).unit = unit;

	// post("price", { material_id: id }).then(({ data, total }) => {
	// 	if (total > 0) {
	// 		const { price } = data[0];
	// 		//赋值给基准价
	// 		formState.value.materials.map(d => {
	// 			d.without_tax_subprice_base = 0;
	// 			d.without_tax_subprice_base_disabled = "";
	// 			if (d.id === id) {
	// 				d.without_tax_subprice_base = price;
	// 				d.without_tax_subprice_base_disabled = true;
	// 			}
	// 			return d;
	// 		});
	// 	} else {
	// 		formState.value.materials.map(d => {
	// 			if (d.id === id) {
	// 				d.without_tax_subprice_base = 0;
	// 				d.without_tax_subprice_base_disabled = false;
	// 			}
	// 			return d;
	// 		});
	// 	}
	// });
};
/**
const copyMaterialModel = record => {
	formState.value.materials.push({ ...record, key: formState.value.materials.length });
}; */

const deleteMaterialModel = key => {
	const { materials } = formState.value;

	const index = materials.findIndex(d => d.key === key);
	if (index === false) return;
	materials.splice(index, 1);

	formState.value = {
		...formState.value,
		materials: materials.map((d, i) => {
			d.key = i;
			return d;
		})
	};
	calAmount();
};

const addArtIndex = () => {
	if (!formState.value.art_indexes) {
		formState.value.art_indexes = [];
	}
	formState.value.art_indexes.push({
		gonghao_id: null,
		price: null,
	})
}
const delArtIndex = (i) => {
	formState.value.art_indexes.splice(i, 1);
}

const changeArtIndex = (record) => {
	const gonghaoIdMap = {};
	for (const item of formState.value.art_indexes) {
		if (!item.gonghao_id) continue;
		if (gonghaoIdMap[item.gonghao_id] > 0) {
			record.gonghao_id = null;
			proxy.$message.error("请勿选择相同的技术指标");
			break;
		} else
			gonghaoIdMap[item.gonghao_id] = 1;
	}
}

const submitPurchase = () => {
	proxy.$message.success("合同提交成功", 1);
	closeTab("/contract");
};

//调用父页面closeTab方法
/*
//父页面定义closeTab方法
provide("closeTab", path => {
	
});
*/
const closeTab = inject("closeTab");
</script>

<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;

	h2 {
		font-size: 16px;
		font-weight: 600;
		line-height: 30px;
		margin-bottom: 20px;
	}

	h3 {
		line-height: 40px;
		font-size: 16px;
		font-weight: 400;
		margin-bottom: 20px;

		display: flex;
		align-items: center;

		&:before {
			content: "";
			display: block;
			width: 2px;
			height: 20px;
			background: rgb(24, 144, 255);
			margin-right: 10px;
		}
	}

	h4 {
		font-weight: 600;
		margin: 15px 0;
		line-height: 30px;
	}
}

:deep(.ant-table-cell) .ant-form-item {
	margin-bottom: 0;

	.ant-form-item-explain {
		position: absolute;
		bottom: -24px;
	}
}

.cache-btn {
	background-color: #0d9424;
	color: #fff;
}
</style>
